package com.roger.mybatisplus.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.roger.mybatisplus.demo.entity.SysUser;
import com.roger.mybatisplus.demo.entity.SysUserQto;
import com.roger.mybatisplus.demo.entity.SysUserVo;
import com.roger.mybatisplus.demo.service.SysUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
public class TestController {

    @Resource
    private SysUserService sysUserService;

    @GetMapping("/testGet/{current}")
    public Page<SysUser> testGet(@PathVariable Integer current){
        return sysUserService.findByPage(current);

    }

    @PostMapping("/testPost/{current}/{size}")
    public QueryResult testPost(@PathVariable Integer current, @PathVariable Integer size, @RequestBody SysUserQto qto){
        Page<SysUserVo> result = sysUserService.findPageByCondition(current, size, qto);
        QueryResult qr = new QueryResult();
        qr.setDataList(result.getRecords());
        qr.setTotalSize(result.getTotal());
        return qr;
    }

    //value1：线程不安全
    private static int value1 = 0;
    //value2：使用乐观锁
    private static AtomicInteger value2 = new AtomicInteger(0);
    //value3：使用悲观锁
    private static int value3 = 0;
    private static synchronized void increaseValue3(){
        value3++;
    }

    public static void main(String[] args) throws Exception {
        //开启1000个线程，并执行自增操作
        for (int i = 0; i < 1000; ++i) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MICROSECONDS.sleep(100);
                        //Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    value1++;
                    value2.getAndIncrement();
                    increaseValue3();
                }
            }).start();
        }
        //打印结果
        Thread.sleep(1000);
        System.out.println("线程不安全：" + value1);
        System.out.println("乐观锁(AtomicInteger)：" + value2);
        System.out.println("悲观锁(synchronized)：" + value3);
    }
}
